package cn.sh.ideal.elasticsearch.client;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

public class ElasticsearchClient { 

	public static TransportClient client; 
	
	public static TransportClient getClient(){
		return client;
	}

	public ElasticsearchClient(String host, String clusterName) {
		// 装载配置文件
		Settings settings = Settings.builder().put("cluster.name", clusterName)
				.build();
		client = new PreBuiltTransportClient(settings);
		//如果包含逗号，则有多台服务器
		if(host.contains(",")){
			String[] hostArray = host.split(",");
			String ip = "";
			int port = 0;
			for (String perHost : hostArray) {
				ip = perHost.split(":")[0];
				port = Integer.valueOf(perHost.split(":")[1]);
				try {
					client.addTransportAddress(new InetSocketTransportAddress(InetAddress
							.getByName(ip), port));
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
			}
		}else{
			String ip = host.split(":")[0];
			int port = Integer.valueOf(host.split(":")[1]);
			try {
				client.addTransportAddress(new InetSocketTransportAddress(InetAddress
						.getByName(ip), port));
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}
		}
	}
}
